package ru.ifmo.swing.genetics.selection;

import org.uncommons.watchmaker.framework.EvaluatedCandidate;
import org.uncommons.watchmaker.framework.SelectionStrategy;
import ru.ifmo.swing.EvolutionControlWithConfigProvider;
import ru.ifmo.swing.genetics.config.common.Chooser;
import ru.ifmo.swing.genetics.config.common.ChooserListener;

import javax.swing.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author avhaliullin
 */
public class SelectionStrategyChooser<T> implements SelectionStrategy<T>, EvolutionControlWithConfigProvider {
    public Map<String, Object> getParamValues() {
        Map<String, Object> res = new HashMap<String, Object>();
        SelectionStrategy strategy = chooser.getItem();
        res.put("Selected strategy", strategy);
        return res;
    }


    private Chooser<SelectionStrategy<? super T>> chooser;
    private SelectionStrategy<? super T> selectionStrategy;

    public SelectionStrategyChooser(Map<String, SelectionStrategy<? super T>> options) {
        chooser = new Chooser<SelectionStrategy<? super T>>(options);
        chooser.addListener(new ChooserListener<SelectionStrategy<? super T>>() {
            public void chosen(SelectionStrategy<? super T> selection) {
                selectionStrategy = selection;
            }
        });
    }

    public JComponent getControl() {
        return chooser;
    }

    public void reset() {
        chooser.reset();
    }

    public void setDescription(String description) {
        chooser.setTitle(description);
    }

    public <S extends T> List<S> select(List<EvaluatedCandidate<S>> population, boolean naturalFitnessScores, int selectionSize, Random rng) {
        return selectionStrategy.select(population, naturalFitnessScores, selectionSize, rng);
    }
}
